import datetime
import random

from flask import current_app
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db
from info import models
# from PIL import Image
# 创建app，并传入配置
from info.models import User

app = create_app("development")
# 添加flask_script和数据库迁移命令
manager = Manager(app)
# 数据库迁移
Migrate(app,db)
manager.add_command("db", MigrateCommand)


@manager.option('-n', '-name', dest='name')
@manager.option('-p', '-password', dest='password')
def createsuperuser(name, password):
    """创建管理员用户"""
    if not all([name, password]):
        print('参数不足')
        return

    user = User()
    user.mobile = name
    user.nick_name = name
    user.password = password
    user.is_admin = True

    try:
        db.session.add(user)
        db.session.commit()
        print("创建成功")
    except Exception as e:
        print(e)
        db.session.rollback()

#添加测试用户
@manager.option('-n', '--name', dest='name')
def add_test_users(name):

    #用户列表容器
    user_list = []

    for num in range(0,1000):
        #创建用户对象
        user = User()

        #设置属性
        user.mobile = "138%08d"%num
        user.nick_name = "138%08d"%num
        user.password_hash = "pbkdf2:sha256:50000$YYAGSAZY$2d2a6bdf9b3a142c14c5c15b62c93603caff7542afa5c80ec9f7e2a880efcf4b"
        #近一个月用户登陆时间
        user.last_login = datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0,3600*24*31))
        #添加到用户列表
        user_list.append(user)

    #添加到数据库中
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return "添加失败"

    return "添加成功"
if __name__ == '__main__':
    manager.run()